﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;
using Mysqlx;
using Mysqlx.Crud;
using Meiam.System.Core;
using MySqlX.XDevAPI;
using System.Net.Http;
using System.Security.Policy;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    ///  组件CRM_客户签收台账自动收入确认
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CRMSignRecognitionController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;
        public readonly string con_oa;
        public readonly string gz_con;
        public readonly string erp_con;


        public CRMSignRecognitionController(ILogger<CRMSignRecognitionRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_oa = _configuration.GetConnectionString("OA_DbConnection");
            gz_con = _configuration.GetConnectionString("GZ_WMS_DbConnection");
            erp_con = _configuration.GetConnectionString("ERP_CRMDbConnection");
            _logger = loggerFactory.CreateLogger<CRMSignRecognitionController>();
        }

        /// <summary>
        /// 组件CRM_客户签收台账自动收入确认
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostOCRRecognition([FromBody] CRMSignRecognitionRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            CRMOCRSignResponseDto re = new CRMOCRSignResponseDto();
            string source_no = "OCRDL-" + DateTimeOffset.Now.ToUnixTimeSeconds().ToString();

            string transaction_date = DB.ToDateTime(DateTime.Now).AddMinutes(-5).ToString("yyyy-MM-dd HH:mm:ss");


            try
            {
                dic = new Dictionary<string, string>(); //查询公用dic
                dic.Add("source_no", "");
                DataTable sor_dt = MethodHelp.GetTableInfo("TMS0212", dic,con);//获取自动收入确认数据源
                if (sor_dt.Rows.Count>0)
                {
                    foreach (DataRow item in sor_dt.Rows)
                    {
                        string err_str = "";//错误信息
                        string check_sqlid = "";//是否集中销售
                        string ORG_NAME = "";
                        string ORGANIZATION_NAME = "";
                        string erp_shipment_no = "";//发运行号

                        dic = new Dictionary<string, string>(); //查询公用dic
                        dic.Add("tz_code", item["source_no"].ToString());
                        DataTable dt_check = MethodHelp.GetTableInfo("TMS0231", dic,con);
                        if (dt_check.Rows.Count<=0)
                        {
                            source_no = source_no + item["source_no"].ToString();//每次调用使用 唯一号+签收台账流水
                            ERP_OMShipOracleERPRequestDto input = new ERP_OMShipOracleERPRequestDto();
                            List<ERP_OMShipOracleERP_DataRequestDto> details = new List<ERP_OMShipOracleERP_DataRequestDto>();

                            if (item["affiliated_organization"].ToString() == "241")
                            {
                                check_sqlid = "TMS0213";//直销数据对比
                            }
                            else
                            {
                                check_sqlid = "TMS0214";//集中销售数据对比
                            }

                            dic = new Dictionary<string, string>(); //查询公用dic
                            dic.Add("ORGANIZATION_ID", item["affiliated_organization"].ToString());
                            string strSql_o = MethodHelp.GetTranSQL("TMS0217", dic, con);//获取WMS送货数据SQL
                            if (strSql_o != "")
                            {
                                DataTable dt_erp_o = DB.OracleQuery(strSql_o, erp_con);
                                if (dt_erp_o.Rows.Count > 0)
                                {
                                    ORG_NAME = dt_erp_o.Rows[0]["ORG_NAME"].ToString();
                                    ORGANIZATION_NAME = dt_erp_o.Rows[0]["ORGANIZATION_NAME"].ToString();

                                    dic = new Dictionary<string, string>();
                                    dic.Add("source_no", item["source_no"].ToString());
                                    DataTable sr_dt = MethodHelp.GetTableInfo(check_sqlid, dic, con);//OCR数据与签收台账数据对比
                                    if (sr_dt.Rows.Count > 0)
                                    {
                                        //ERP待发运确认数据获取
                                        dic = new Dictionary<string, string>(); //查询公用dic
                                        dic.Add("WMS_SOURCE_NUM", sr_dt.Rows[0]["shiporder_no"].ToString());
                                        dic.Add("SOURCE_HEADER_NUMBER", sr_dt.Rows[0]["sales_order_number"].ToString());
                                        dic.Add("PICKED_QUANTITY", sr_dt.Rows[0]["signed_quantity"].ToString());
                                        dic.Add("LINE_NUMBER", sr_dt.Rows[0]["sales_order_line_number"].ToString());
                                        string strSql2 = MethodHelp.GetTranSQL("TMS0215", dic, con);//获取WMS送货数据SQL
                                        if (strSql2 != "")
                                        {
                                            DataTable dt_cb = DB.OracleQuery(strSql2, erp_con);
                                            if (dt_cb.Rows.Count > 0)
                                            {
                                                erp_shipment_no = dt_cb.Rows[0]["LINE_SHIPMENT_NUMBER"].ToString();
                                                dic = new Dictionary<string, string>(); //查询公用dic
                                                dic.Add("WMS_SOURCE_NUM", dt_cb.Rows[0]["WMS_SOURCE_NUM"].ToString());
                                                dic.Add("SOURCE_HEADER_NUMBER", dt_cb.Rows[0]["SOURCE_HEADER_NUMBER"].ToString());
                                                dic.Add("LINE_SHIPMENT_NUMBER", dt_cb.Rows[0]["LINE_SHIPMENT_NUMBER"].ToString());
                                                string strSql3 = MethodHelp.GetTranSQL("TMS0216", dic, con);//获取WMS送货数据SQL
                                                if (strSql3 != "")
                                                {
                                                    DataTable dt_fh_erp = DB.OracleQuery(strSql3, erp_con);
                                                    if (dt_fh_erp.Rows.Count > 0)
                                                    {
                                                        foreach (DataRow erp_d in dt_fh_erp.Rows)
                                                        {
                                                            details.Add(new ERP_OMShipOracleERP_DataRequestDto
                                                            {
                                                                SCUX_SOURCE_NUM = source_no,
                                                                SOURCE_SYSTEM = "CRM",
                                                                ORG_NAME = ORG_NAME,
                                                                ORGANIZATION_NAME = ORGANIZATION_NAME,
                                                                ORDER_NUMBER = erp_d["SOURCE_HEADER_NUMBER"].ToString(),
                                                                LINE_NUMBER = erp_d["LINE_NUMBER"].ToString(),
                                                                SHIPMENT_NUMBER = erp_d["SHIPMENT_NUMBER"].ToString(),
                                                                DELIVERY_DETAIL_ID = erp_d["DELIVERY_DETAIL_ID"].ToString(),
                                                                TRANSACTION_QUANTITY = erp_d["PICKED_QUANTITY"].ToString(),
                                                                CONFIRM_TYPE = "A",
                                                                TRANSACTION_DATE = transaction_date,
                                                                LOT_NUMBER = null,
                                                            });
                                                        }

                                                        if (details.Count > 0 && err_str == "")
                                                        {
                                                            input.PV_SOURCE_SYS_CODE = "CRM";
                                                            input.PV_BUSINESS_TYPE_CODE = "CRM_OM_SHIP";
                                                            input.PV_SYNCHRO_FLAG = "Y";
                                                            input.ROWS = details;

                                                            Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                                            urldic.Add("function_description", "内部:ERP发运确认");//查看URL配置表地址描述
                                                            DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                                            if (url_dt.Rows.Count > 0)
                                                            {
                                                                string jsonText = JsonConvert.SerializeObject(input);
                                                                var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                                                ERP_OMShipOracleERPResponseDto psp = JsonConvert.DeserializeObject<ERP_OMShipOracleERPResponseDto>(reAgv);
                                                                if (psp.statusCode > 0)
                                                                {
                                                                    err_str = "ERP返回错误:" + psp.message;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                            else
                                            {
                                                err_str = "出库单=<" + sr_dt.Rows[0]["shiporder_no"].ToString() + ">，销售订单=<" + sr_dt.Rows[0]["sales_order_number"].ToString() + ">,行号=<" + sr_dt.Rows[0]["sales_order_line_number"].ToString() + ">,出库数量=<" + sr_dt.Rows[0]["signed_quantity"].ToString() + ">找不到ERP相关数据，自动确认失败！";
                                            }
                                        }

                                    }
                                    else
                                    {
                                        err_str = "找不到签收台账=<" + item["source_no"].ToString() + ">数据记录,OCR识别数据与签收台账记录数据匹配失败，自动收入确认失败！";
                                    }
                                }
                            }
                        }
                        else
                        {
                            err_str = "台账流水号=<" + item["source_no"].ToString() + ">存在手工申请《客户签收申请》，自动收入确认ERP确认终止！";
                        }

                       

                        if (err_str!="")
                        {
                            dic = new Dictionary<string, string>(); //查询公用dic
                            dic.Add("erp_push_no", source_no);
                            dic.Add("push_desc", err_str);
                            dic.Add("code", item["source_no"].ToString());
                            strMsg=MethodHelp.InsertIntoTable("TMS0218", dic,con);

                        }
                        else
                        {
                            dic = new Dictionary<string, string>(); //查询公用dic
                            dic.Add("erp_push_no", source_no);
                            dic.Add("erp_shipment_no", erp_shipment_no);
                            dic.Add("code", item["source_no"].ToString());
                            strMsg = MethodHelp.InsertIntoTable("TMS0219", dic, con);
                        }

                    }                  
                }            
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
